package com.shiningstars.service;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.app.NotificationCompat;

import com.parse.ParsePush;
import com.shiningstars.R;
import com.shiningstars.activity.MSLocatorActivity;
import com.shiningstars.database.DatabaseHandler;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.Messages;
import com.shiningstars.general.Utilities;
import com.shiningstars.php.WebHelper;
import com.shiningstars.tools.ExceptionHandler;
import com.shiningstars.valuebeans.MsLocation;

public class MSLocatorService extends Service implements Constants, Config, Messages {

	int attempts = SERVICE_ATTEMPTS;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

		final WebHelper webHelper = new WebHelper();
		final DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getApplicationContext());

		new Thread() {
			@Override
			public void run() {

				Looper.prepare();

				while (attempts > 0) {
					attempts--;
					MsLocation msLocation = databaseHandler.getMsLocation();

					try {
						if (null != msLocation) {
							if (msLocation.getIsSynced().equals(N)) {

								JSONObject json = webHelper.sendMsLocation(msLocation, getApplicationContext());

								if (null != json && json.getBoolean(SUCCESS)) {
									long msLocationId = json.getLong(MS_LOCATION_ID);
									databaseHandler.updateMsLocationIsSync(msLocation.getId(), msLocationId);

									JSONObject pushJSON = new JSONObject();
									pushJSON.put(ACTION, START_SERVICE);
									pushJSON.put(SERVICE_NAME, MS_LOCATOR_SERVICE);

									ParsePush push = new ParsePush();
									push.setData(pushJSON);
									push.sendInBackground();

									databaseHandler.updateMsLocationIsNotified(msLocation.getId(), Y);
								}

							} else if (msLocation.getIsNotified().equals(N)) {
								JSONObject pushJSON = new JSONObject();
								pushJSON.put(ACTION, START_SERVICE);
								pushJSON.put(SERVICE_NAME, ALL);

								ParsePush push = new ParsePush();
								push.setData(pushJSON);
								push.sendInBackground();

								databaseHandler.updateMsLocationIsNotified(msLocation.getId(), Y);
							}

							updateMsLocation(msLocation.getMsLocationId(), webHelper, databaseHandler);
						} else {
							updateMsLocation(0, webHelper, databaseHandler);
						}

					} catch (IllegalStateException e) {
						Utilities.logError(getApplicationContext(), MSLocatorService.class.getName(), e);
					} catch (JSONException e) {
						Utilities.logError(getApplicationContext(), MSLocatorService.class.getName(), e);
					} catch (IOException e) {
					}

					try {
						Thread.sleep(SERVICE_THREAD_SLEEP);
					} catch (InterruptedException e) {
						Utilities.logError(getApplicationContext(), MSLocatorService.class.getName(), e);
					}
				}

				stopService(new Intent(getApplicationContext(), MSLocatorService.class));

				Looper.loop();
				Looper.myLooper().quit();
			}
		}.start();

		return START_NOT_STICKY;
	}

	private void updateMsLocation(long msLocationId, final WebHelper webHelper, final DatabaseHandler databaseHandler)
			throws IllegalStateException, IOException, JSONException {
		JSONObject json = webHelper.getMsLocation(msLocationId, getApplicationContext());

		if (null != json && json.getBoolean(SUCCESS)) {
			MsLocation location = new MsLocation();
			location.setMsLocationId(json.getLong(MS_LOCATION_ID));
			location.setPlace(json.getString(PLACE));
			location.setStayDuration(json.getString(STAY_DURATION));
			location.setContactPerson(json.getString(CONTACT_PERSON));
			location.setComments(json.getString(COMMENTS));
			location.setPostedBy(json.getString(POSTED_BY));
			location.setPostedOn(json.getString(POSTED_ON));
			location.setIsSynced(Y);
			location.setIsNotified(Y);

			databaseHandler.updateMsLocation(location);

			String name = Utilities.getSharedPreference(getApplicationContext(), NAME);
			String mobileNumber = Utilities.getSharedPreference(getApplicationContext(), MOBILE_NUMBER);

			if (!location.getPostedBy().equals(name + NEW_LINE + mobileNumber)) {

				Intent intent = new Intent(getApplicationContext(), MSLocatorActivity.class);
				PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
				Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

				long pattern[] = { 0, 100, 200, 300, 400 };

				NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
						.setContentTitle(SSP).setSmallIcon(R.drawable.ic_launcher).setContentIntent(pendingIntent)
						.setAutoCancel(true).setSound(notificationSound).setVibrate(pattern);

				builder.setContentText(MS_LOCATION_UPDATED);
				NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
				notificationManager.notify(0, builder.build());

			}
		}
	}
}